<!-- 继承页面模板 -->
{% extends 'layout/layui_base_page.html' %}

<!-- 加载静态文件 -->
{% load static %}

<!-- Title -->
{% block title %}
    培训基础信息
{% endblock %}

<!-- CSS --->
{% block css %}
    <style>
        .layui-card {
            border: 1px solid lightgray;
            box-sizing: border-box;
            height: 350px;
        }

        .layui-card:hover {
            box-shadow: 0 0 8px rgba(0, 0, 0, 0.2);
        }

        .addPostion:hover {
            color: lightblue;

        }

        .positionItem:hover {
            background-color: rgba(0, 0, 0, 0.1);
        }

        .h5title:hover {
            background-color: lightgrey;
            color: navy;
            font-size: 16px;
            font-weight: bold;
        }

        .positionItem:hover {
            background-color: lightgray;
            font-weight: bold;
            color: navy;
        }
    </style>
{% endblock %}

<!-- Content -->
{% block content %}
    <!-- 01: 面包屑导航 -->
    <span class="layui-breadcrumb">
      <a href="javascript:;">首页</a>
      <a href="javascript:;">基础数据</a>
      <a><b>培训基础信息</b></a>
    </span>

    <!-- 02: 查询区域 --->
    <div id="queryArea" style="margin-top: 20px;">
        <form class="layui-form">
            {% csrf_token %}
            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label" for="q_str"><b>查询条件：</b></label>
                    <div class="layui-input-inline">
                        <input type="text" name="q_str" id="q_str" class="layui-input">
                    </div>
                </div>
                <div class="layui-inline">
                    <button type="button" class="layui-btn" id="btnQuery" style="width: 120px"><i
                            class="fa fa-search"></i>&nbsp;&nbsp;查询
                    </button>
                    <button type="button" class="layui-btn" id="btnAll" style="width: 120px"><i class="fa fa-list"></i>&nbsp;&nbsp;全部
                    </button>
                    <button type="button" class="layui-btn" id="btnAddDept" style="width: 120px"><i
                            class="fa fa-plus-circle"
                            aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;添加部门
                    </button>
                </div>
            </div>
        </form>

    </div>

    <!-- 03：表格区域 -->
    <div id="contentArea" style="overflow: hidden;">
        <div class="layui-bg-gray">
            <div class="layui-row layui-col-space15" id="cardArea" style="top: 20px;padding: 5px">
            </div>
        </div>
    </div>

    <!-- 04: 管理阶段、阶段内容 -->
    <div id="phaseLayer" style="display: none; padding: 10px 40px;">
        <form class="layui-form">
            {% csrf_token %}
            <div class="layui-form-item">
                <div class="layui-inline" style="width: 220px">
                    <label class="layui-form-label"><b>产线：</b></label>
                    <div class="layui-input-block">
                        <input type="text" name="line" id="line" class="layui-input" readonly
                               style="background-color: #eaeaea">
                    </div>
                </div>

                <div class="layui-inline" style="width: 220px">
                    <label class="layui-form-label"><b>部门：</b></label>
                    <div class="layui-input-block">
                        <input type="text" name="department" id="department" class="layui-input" readonly
                               style="background-color: #eaeaea">
                    </div>
                </div>


                <div class="layui-inline" tyle="width: 220px">
                    <label class="layui-form-label"><b>职位：</b></label>
                    <div class="layui-input-block">
                        <input type="text" name="position" id='position' class="layui-input" readonly
                               style="background-color: #eaeaea">
                    </div>
                </div>

                <div class="layui-inline">
                    <button type="button" class="layui-btn" id="btnAddPhase" style="width: 120px"><i
                            class="fa fa-plus-circle"
                            aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;添加阶段
                    </button>
                </div>

            </div>
        </form>
        <fieldset class="layui-elem-field layui-field-title" style="margin-top: 50px;">
            <legend><b>阶段和阶段内容</b></legend>
        </fieldset>
        <div id="phaseArea"></div>

    </div>
{% endblock %}

<!-- JS -->
{% block js %}
    <script>
        // 入口函数
        $(function () {
            // === 页面初始化 ===
            initPage();
            // === 初识化数据 ===
            initData();
            // ==== 响应点击事件 ====
            buttonClick();

        });

        // ================ 页面初始化的实现 ==================
        function initPage() {
            layui.use(['element'], function () {
                let element = layui.element;
            })
        }

        // ============== 初始化数据 ==========================
        function initData() {
            // === Ajax请求所有的部门 =====
            $.ajax({
                url: "{% url 'get_department_data' %}"
                , method: 'post'
                , data: {
                    q_str: $('#q_str').val(),
                    csrfmiddlewaretoken: "{{ csrf_token }}"
                }
                , success: function (res) {

                    buildDepartment(res.data);

                }
            })
        }

        // ================= 构建部门的前端展示 =================
        function buildDepartment(data) {
            // 获取顶级的父容器
            let topContainer = $('#cardArea');
            //清空
            topContainer.empty();
            // 开始遍历数据
            $.each(data, (index, value) => {
                // 新建一层div
                let oneLevelDiv = $('<div>').attr({'class': 'layui-col-md3'}).appendTo(topContainer);
                // 新建二层div
                let twoLevelDiv = $('<div>').attr({
                    'class': 'layui-card',
                    'style': 'height:340px; background-color:#F5FFE8',
                }).appendTo(oneLevelDiv);
                // 新建卡片的标题
                let cardTitle = $('<div>').attr({
                    'class': 'layui-card-header layui-row',
                    'style': 'border-bottom: 1px solid grey'
                }).appendTo(twoLevelDiv);
                // 新建卡片标题
                let cardTitleName = $('<div>').attr({'class': 'layui-col-lg6'}).html("<b style='color:darkred;font-size：'16px'>" + value.name + "</a></b>").appendTo(cardTitle);
                let cartTitleButton = $('<div>').attr({
                    'class': 'layui-col-lg6',
                    style: 'text-align:right;'
                }).appendTo(cardTitle);
                // 新建第三个按钮
                $('<a>').attr({
                    href: "javascript:;",
                    class: 'layui-btn layui-btn-xs layui-btn-normal editDepartment',
                    id: value.id,
                    name: value.name,
                    title: '编辑部门'
                }).html("<i class='fa fa-edit' aria-hidden='true'></i>").appendTo(cartTitleButton);
                $('<a>').attr({
                    href: "javascript:;",
                    class: 'layui-btn layui-btn-xs layui-btn-danger delDepartment',
                    id: value.id,
                    name: value.name,
                    title: '删除部门'
                }).html("<i class='fa fa-trash' aria-hidden='true'></i>").appendTo(cartTitleButton);
                $('<a>').attr({
                    href: "javascript:;",
                    class: 'layui-btn layui-btn-xs addPosition',
                    id: value.id, // 部门Id
                    title: '添加职位'
                }).html("<i class='fa fa-plus-circle' aria-hidden='true'></i>&nbsp 职位").appendTo(cartTitleButton)
                // 新建卡片的内容
                let cardBody = $('<div>').attr({'class': 'layui-card-body'}).html(buildPosition(value)).appendTo(twoLevelDiv)
            })
        }

        // ================= 构建职位的前端展示 =================
        function buildPosition(department_data) {
            // 新建ul标签
            let ulContainer = $('<ul>');
            // 遍历数据
            $.each(department_data.position, (index, value) => {
                let liContainer = $('<li>').attr({
                    'class': 'positionItem',
                    style: "line-height: 30px;",
                }).appendTo(ulContainer);
                // 栅格系统的div
                let row = $('<div>').attr({'class': 'layui-row'}).appendTo(liContainer);
                // 左边的标题
                let row_left = $('<div>').attr({'class': 'layui-col-lg6'}).html("<i class='fa fa-id-card-o' aria-hidden='true'></i> &nbsp" + value.name).appendTo(row)
                // 右边的三个按钮
                let row_right = $('<div>').attr({'class': 'layui-col-lg6', 'style': 'text-align:right;'}).appendTo(row);
                // 新建第一个按钮 --- 编辑
                $('<a>').attr({
                    href: "javascript:;",
                    class: 'layui-btn layui-btn-xs layui-btn-normal editPosition',
                    id: value.id,
                    name: value.name,
                    tag: department_data.id,
                    title: '编辑职位'
                }).html("<i class='fa fa-edit' aria-hidden='true'></i>").appendTo(row_right);
                // 新建第二个按钮 --- 删除
                $('<a>').attr({
                    href: "javascript:;",
                    class: 'layui-btn layui-btn-xs layui-btn-danger delPosition',
                    id: value.id,
                    name: value.name,
                    title: '删除职位'
                }).html("<i class='fa fa-trash' aria-hidden='true'></i>").appendTo(row_right);
                // 新建第三个按钮 --- 培训内容明细
                $('<a>').attr({
                    href: "javascript:;",
                    class: 'layui-btn layui-btn-xs phaseDetail',
                    tag: JSON.stringify(department_data),
                    id: value.id,
                    name: value.name,
                    title: '管理培训具体内容'
                }).html("<i class='fa fa-edit' aria-hidden='true'></i>&nbsp 内容").appendTo(row_right)
            });

            return ulContainer

        }


        // ============== 构建职位 ===========================
        /*
        function buildPosition(data) {
            // 新建ul
            let ulContainer = $('<ul>');
            // 遍历
            $.each(data.position, (index, value) => {
                let liContainer = $('<li>').attr({
                    'id': value.id,
                    'class': 'positionItem',
                    'width': '100%',
                }).appendTo(ulContainer);

                $('<span>').css({
                    width: '50%',
                }).html("<b style='color:navy;font-size:16px;line-height:30px;'><i class=\"fa fa-id-card-o\" aria-hidden=\"true\"></i> " + value.name + "</b>").appendTo(liContainer);

                let rightSpan = $('<span>').attr({
                    style: "line-height:25px;",
                }).appendTo(liContainer);

                $('<a>').attr({
                    class: "layui-btn-xs layui-btn-warm viewDetail",
                    style: "float:right;color:white; margin-left:5px;",
                    href: 'javascript:;',
                    id: value.id,
                    name: value.name,
                    tag: JSON.stringify(data),
                    title: '管理职位培训内容',
                }).html("<i class=\"fa fa-plus-circle\" aria-hidden=\"true\">&nbsp;&nbsp;培训内容").appendTo(rightSpan);

                $('<a>').attr({
                    class: "layui-btn-xs layui-btn-normal editPosition",
                    style: "float:right;color:white;margin-left:5px;",
                    href: 'javascript:;',
                    id: value.id,
                    title: '编辑职位',
                }).html(" <i class=\"fa fa-edit\" aria-hidden=\"true\"></i>").appendTo(rightSpan);

                $('<a>').attr({
                    class: "layui-btn-xs layui-btn-normal delPosition",
                    style: "float:right;color:white;margin-left:5px;",
                    href: 'javascript:;',
                    id: value.id,
                    title: '删除职位',
                }).html(" <i class=\"fa fa-trash\" aria-hidden=\"true\"></i>").appendTo(rightSpan);


            });

            return ulContainer
        }
        */

        // ===============响应点击事件的实现 ===========================
        function buttonClick() {

            // === 查询 ====
            $('#btnQuery').on('click', function () {
                initData();
            });
            // === 显示全部 ===
            $('#btnAll').on('click', function () {
                // 清除条件
                $('#q_str').val("");
                // 重新加载
                initData();
            });

            // === 添加部门 ===
            $('#btnAddDept').on('click', function () {
                // 添加部门 --- 弹出一个文本输入
                layui.layer.prompt({
                    title: "请输入要添加的部门名称，并点击确定",
                    btn: ['确定', '取消'],
                    formType: 0  // 0(单行文本输入), 1（密码输入） , 2（多行文本输入）
                }, function (value) {
                    // -- 使用Ajax调用后台添加接口 ---
                    $.ajax({
                        url: "{% url 'add_department' %}"
                        , method: 'post'
                        , data: {
                            name: value,
                            line: {{ request.session.current_line }},
                            csrfmiddlewaretoken: "{{ csrf_token }}"
                        }
                        , dataType: 'json'
                        , success: function (res) {
                            if (res.status) {
                                layui.layer.msg("部门添加成功！");
                                location.reload();
                            } else {
                                layui.layer.msg(res.error, {
                                    icon: 2, area: ['400px', '200px'], time: -1, btn: ['关闭']
                                })
                            }
                        }
                    })
                })
            });

            // === 修改部门 ====
            $('body').on('click', '.editDepartment', function () {
                // 获取到当前要编辑的部门的id
                let department_id = $(this).attr('id');
                // 编辑部门 --- 弹出一个文本输入
                layui.layer.prompt({
                    title: "请输入要修改后的部门名称，并点击确定",
                    btn: ['确定', '取消'],
                    value: $(this).attr('name'),
                    formType: 0  // 0(单行文本输入), 1（密码输入） , 2（多行文本输入）
                }, function (value) {
                    // -- 使用Ajax调用后台添加接口 ---
                    $.ajax({
                        url: "{% url 'edit_department' %}"
                        , method: 'post'
                        , data: {
                            department_id: department_id,
                            name: value,
                            csrfmiddlewaretoken: "{{ csrf_token }}"
                        }
                        , dataType: 'json'
                        , success: function (res) {
                            if (res.status) {
                                layui.layer.msg("部门修改成功！");
                                location.reload();
                            } else {
                                layui.layer.msg(res.error, {
                                    icon: 2, area: ['400px', '200px'], time: -1, btn: ['关闭']
                                })
                            }
                        }
                    })
                })
            });

            // === 删除部门 ====
            $('body').on('click', '.delDepartment', function () {
                // 获取到当前要删除的部门的id
                let dept_id = $(this).attr('id');
                let dept_name = $(this).attr('name');
                // 准备确认的文字
                let confirmStr = "您确定要删除【编号：" + dept_id + "  名称：" + dept_name + "】信息吗?";
                // 确认框
                layui.layer.confirm(confirmStr, {
                    icon: 3, title: "删除确认", area: ['400px', '200px'], btn: ['确认', '关闭']
                }, function (index) {
                    // -- 使用Ajax调用后台添加接口 ---
                    $.ajax({
                        url: "{% url 'del_department' %}"
                        , method: 'post'
                        , data: {
                            department_id: dept_id,
                            csrfmiddlewaretoken: "{{ csrf_token }}"
                        }
                        , dataType: 'json'
                        , success: function (res) {
                            if (res.status) {
                                layui.layer.msg("部门删除成功！");
                                location.reload();
                            } else {
                                layui.layer.msg(res.error, {
                                    icon: 2, area: ['400px', '200px'], time: -1, btn: ['关闭']
                                })
                            }
                        }
                    })
                });

            });

            // === 添加职位 ===
            $('body').on('click', '.addPosition', function () {
                // 获取当前部门的Id
                let department_id = $(this).attr("id");

                layui.use(['layer'], function () {
                    let layer = layui.layer;

                    layer.prompt({
                        title: "输入要添加的职位名称，点击确定"
                        , formType: 0
                    }, function (value, index, elem) {
                        // Ajax
                        $.ajax({
                            url: "{% url 'add_position' %}"
                            , method: 'post'
                            , data: {
                                department_id: department_id,
                                position_name: value,
                                csrfmiddlewaretoken: "{{ csrf_token }}"
                            }
                            , success: function (res) {
                                if (res.status) {
                                    layui.layer.msg("职位添加成功！");
                                    location.reload()
                                } else {
                                    layui.layer.msg(res.error, {
                                        icon: 2, area: ['400px', '200px'], time: -1, btn: ['关闭']
                                    })
                                }
                            }
                        })
                    })
                });

            });

            // === 编辑职位 ===
            $('body').on('click', '.editPosition', function () {
                // 获取当前部门的Id
                let department_id = $(this).attr("tag");
                let position_id = $(this).attr("id");
                let position_name = $(this).attr("name");
                layui.use(['layer'], function () {
                    let layer = layui.layer;

                    layer.prompt({
                        title: "输入要修改的职位名称，点击确定"
                        , value: position_name
                        , formType: 0
                    }, function (value, index, elem) {
                        // Ajax
                        $.ajax({
                            url: "{% url 'edit_position' %}"
                            , method: 'post'
                            , data: {
                                department_id: department_id,
                                position_name: value,
                                position_id: position_id,
                                csrfmiddlewaretoken: "{{ csrf_token }}"
                            }
                            , success: function (res) {
                                if (res.status) {
                                    layui.layer.msg("职位修改成功！");
                                    location.reload()
                                } else {
                                    layui.layer.msg(res.error, {
                                        icon: 2, area: ['400px', '200px'], time: -1, btn: ['关闭']
                                    })
                                }
                            }
                        })
                    })
                });

            });

            // === 删除职位 ===
            $('body').on('click', '.delPosition', function () {
                // 获取当前部门的名字和Id
                let position_id = $(this).attr('id');
                let position_name = $(this).attr('name');
                // 提示
                let confirmStr = "您确定要删除职位【名称：" + position_name + "】的信息吗？";
                // 使用layui.layer
                layui.use(['layer'], function () {
                    let layer = layui.layer;

                    layer.confirm(confirmStr, {
                        icon: 3, area: ['400px', '200px'], btn: ['确认', '取消']
                    }, function (index) {
                        // ajax请求
                        $.ajax({
                            url: "{% url 'del_position' %}"
                            , method: 'post'
                            , data: {
                                position_id: position_id,
                                csrfmiddlewaretoken: "{{ csrf_token }}"
                            }
                            , success: function (res) {
                                if (res.status) {
                                    layui.layer.msg("职位删除成功！")
                                    location.reload()
                                } else {
                                    layui.layer.msg(res.error, {
                                        icon: 2, area: ['400px', '200px'], time: -1, btn: ['关闭']
                                    })
                                }
                            }
                        })
                    })
                })
            });


            // === 管理阶段和阶段内容 ===
            $('body').on('click', '.phaseDetail', function () {
                // 获取当前部门的信息
                let infos = JSON.parse($(this).attr('tag'));
                // 获取当前的职位
                infos.position_id = $(this).attr('id');
                infos.position_name = $(this).attr('name');
                console.log(infos);
                //传数据给子页面
                window.INFOS = infos;
                layui.use(['layer'], function () {
                    let layer = layui.layer;

                    layer.open({
                        type: 2
                        , title: "<b style='color:navy'>【管理阶段和阶段内容】</b>"
                        , area: ['100%', '100%']
                        , offset: ['0px', '0px']
                        , zindex: 10
                        , fixed: false
                        , maxmin: true
                        , content: "{% url 'phase_phasecontent_page' %}"
                    })
                })
            })

            // === 培训内容的详情 ===
            /*
            $('body').on('click', '.viewDetail', function () {
                // 获取当前职位的编号
                let data = JSON.parse($(this).attr('tag'));
                data.position_id = $(this).attr('id');
                data.position_name = $(this).attr('name');

                // 弹出层
                loadPhaseContentLayer(data);

            })*/
        }

        // ================ 展示阶段和阶段内容的弹出层 =================
        function loadPhaseContentLayer(value) {
            layui.use(['layer', 'form', 'element'], function () {
                let layer = layui.layer;
                let form = layui.form;
                let element = layui.element;

                layer.open({
                    type: 1
                    , title: "<b style='color:navy'>【管理阶段和阶段内容】</b>"
                    , content: $('#phaseLayer')
                    , area: ['1050px', '800px']
                    , btn: ['确定', '取消']

                    // ======= 回调函数 =======
                    , success: function (index, layero) {
                        // ===1. 初始化表单中产线，部门和职位的展示===
                        $('#line').val(value.line_name);
                        $('#department').val(value.name);
                        $('#position').val(value.position_name);

                        //-- 2. 获取当前职位的阶段以及阶段内容 并填充到页面 ---
                        $.ajax({
                            url: "{% url 'get_phase_phasecontent_data' %}"
                            , method: 'post'
                            , data: {
                                position_id: value.position_id,
                                csrfmiddlewaretoken: "{{ csrf_token }}"
                            }
                            , success: function (res) {
                                // 渲染到页面！！1
                                buildPhase(res.data);
                            }
                        })
                    }
                })
            })
        }

        // =============== 渲染阶段信息 =================
        function buildPhase(data) {
            // 获取当前phase区域
            let topContainer = $('#phaseArea');
            // 清空所有内容
            topContainer.empty();
            // 新建一层内容
            let oneLevelContent = $('<div>').attr({'class': 'layui-collapse'}).appendTo(topContainer);
            // 开始遍历
            $.each(data, (index, value) => {
                // 新建二层内容
                let twoLevelContent = $('<div>').attr({'class': 'layui-colla-item'}).appendTo(oneLevelContent);
                // 新建标题
                let h2Content = $('<h2>').attr({'class': 'layui-colla-title'}).html("<b style='color:navy; font-size:16px'>" + value.phasename__name + "</b>").appendTo(twoLevelContent);

                // 新建内容的div -- <div class="layui-colla-content">
                let bodyContent = $('<div>').attr({'class': 'layui-colla-content'}).html(buildPhaseContent(value.phasecontent)).appendTo(twoLevelContent);
                // element组件初始化
                layui.element.init();
            });
        }

        // ============== 渲染阶段的明细 =================
        function buildPhaseContent(data) {
            // 新建ul
            let ulContainer = $('<ul>').attr({'class': 'layui-timeline'});
            // 循环
            $.each(data, (index, value) => {
                // 新建li标签
                let liContainer = $('<li>').attr({'class': 'layui-timeline-item'}).appendTo(ulContainer);
                // 新建 I标签
                let iContainer = $('<i>').attr({'class': 'layui-icon layui-timeline-axis'}).appendTo(liContainer);
                // 新建div
                let divContainer = $('<div>').attr({'class': 'layui-timeline-content layui-text'}).appendTo(liContainer);
                // 新建h3
                let h5Container = $('<h4>').attr({'class': 'layui-timeline-title h5title'}).html(value.name).appendTo(divContainer);
            });


            return ulContainer
        }


    </script>

{% endblock %}